package com.du.cloud.service.oauth.extend;

import com.du.cloud.security.service.TokenUser;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;

import java.util.Map;

/**
 * Desc: 自定义抽象令牌授予者
 * Author: dushuang
 * Date: 2020/5/29
 **/
public abstract class  AbstractCustomTokenGranter extends AbstractTokenGranter {

    private final OAuth2RequestFactory requestFactory;

    protected AbstractCustomTokenGranter(AuthorizationServerTokenServices tokenServices,
                         ClientDetailsService clientDetailsService,
                         OAuth2RequestFactory requestFactory,
                         String grantType) {
        super(tokenServices, clientDetailsService, requestFactory, grantType);
        this.requestFactory = requestFactory;
    }

    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
        Map<String, String> parameters = tokenRequest.getRequestParameters();
        TokenUser tokenUser = this.getUserDetails(parameters);
        if (tokenUser == null) {
            throw new InvalidGrantException("无法获取用户信息");
        }
        OAuth2Request storedOAuth2Request = this.requestFactory.createOAuth2Request(client, tokenRequest);
        PreAuthenticatedAuthenticationToken authenticationToken = new PreAuthenticatedAuthenticationToken(tokenUser, null, tokenUser.getAuthorities());
        authenticationToken.setDetails(tokenUser);
        OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(storedOAuth2Request, authenticationToken);
        return oAuth2Authentication;
    }

    protected abstract TokenUser getUserDetails(Map<String, String> parameters);
}
